import React, {FC, useEffect, useState} from 'react';
import './styles/UserUpdateModal.css'
import UserInfo from "../../../../models/UserInfo";
import UpdateUserDto from "../../../../utils/dto/user/updateUserDto";
import {updateUserInfo} from "../../../../http/userApi";
import Country from "../../../../models/Country";
import {getCountries} from "../../../../http/countryApi";
import {deleteImage, uploadImage} from "../../../../http/imageApi";
import DeleteImageDto from "../../../../utils/dto/image/deleteImageDto";

interface IUserUpdateModalProps {
    user: UserInfo;
    onClose: () => void;
}

const UserUpdateModal: FC<IUserUpdateModalProps> = ({user, onClose}) => {
    const [userName, setUserName] = useState(user.userName);
    const [firstName, setFirstName] = useState(user.firstName);
    const [lastName, setLastName] = useState(user.lastName);
    const [patronymic, setPatronymic] = useState(user.patronymic);
    const [countryId, setCountryId] = useState<string | null>(null)
    const [userImage, setUserImage] = useState<File | null>(null);
    const [countries, setCountries] = useState<Country[]>([]);

    useEffect(() => {
        const fetchCountries = async () => {
            const response = await getCountries();
            if (response.status === 200) {
                setCountries(response.data.countries);
            } else {
                console.error(response.statusText);
            }
        };

        fetchCountries().catch(error => console.error("Fetch countries failed:", error));
    }, []);

    const handleSubmit = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
        e.preventDefault()
        if (userImage) {
            uploadImage(userImage).then(response => {
                if (response.status !== 200) {
                    console.error(response.statusText);
                } else {
                    let dto = new UpdateUserDto(userName, firstName, lastName, patronymic, countryId, response.data.imageId)
                    updateUserInfo(dto).then(response => {
                            if (response.status === 200) {
                                onClose()
                            } else
                                alert(response.statusText)
                        }
                    )
                }
            })
        }
        
        else{
            let dto = new UpdateUserDto(userName, firstName, lastName, patronymic, countryId, null)
            updateUserInfo(dto).then(response => {
                    if (response.status === 200) {
                        if (response.status === 200)
                            onClose()
                        else
                            alert(response.statusText)
                    } else
                        alert(response.statusText)
                }
            )
        }
    }

    const handleDeleteUserImageClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
        e.preventDefault()
        if (user.imageId) {
            const dto = new DeleteImageDto(user.imageId)
            user.imageId = null
            deleteImage(dto)
                .then(response => {
                    if (response.status === 200)
                        onClose()
                    else
                        alert(response.statusText)
                })
        }
    }

    return (
        <div className="modal">
            <div className="modal-content">
                <h2>Изменение профиля</h2>
                <form>
                    <label>
                        Никнейм:
                        <input type="text" value={userName} onChange={(e) => setUserName(e.target.value)}/>
                    </label>
                    <label>
                        Имя:
                        <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)}/>
                    </label>
                    <label>
                        Фамилия:
                        <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)}/>
                    </label>
                    <label>
                        Отчество:
                        <input type="text" value={patronymic} onChange={(e) => setPatronymic(e.target.value)}/>
                    </label>
                    <label>
                        Фото:
                        <input
                            type="file"
                            onChange={e => {
                                if (e.target.files !== null) {
                                    const file = e.target.files[0]
                                    setUserImage(file)
                                }
                            }}/>
                        <button className="modal-button" onClick={handleDeleteUserImageClick}>Удалить текущую
                            фотографию
                        </button>
                    </label>
                    <label>
                        Страна:
                        <select
                            onChange={(e) => setCountryId(e.target.value)} required>
                            <option value="">Select your country</option>
                            {countries.sort((a, b) => a.countryName.localeCompare(b.countryName)).map(country => (
                                <option key={country.countryId}
                                        value={country.countryId}>{country.countryName}</option>
                            ))}
                        </select>
                    </label>
                    <div className="modal-buttons">
                        <button type="submit" onClick={handleSubmit}>Сохранить</button>
                        <button type="button" onClick={onClose}>Закрыть</button>
                    </div>
                </form>
            </div>
        </div>
    );
}

export default UserUpdateModal;